<template>
  <div class="yxp">
    <div class="yxp-wordList-top">
      <div class="back" id="yxp-before-back" @click="handleBack">
        <span></span>
      </div>
      <span class="yxp-top-c">学前检测</span>
      <div class="yxp-top-r">
        <div class="success">
          <img src="@/assets/word/success-icon.png" />{{ successNum }}词
        </div>
        <div class="error">
          <img src="@/assets/word/error-icon.png" />{{ errorNum }}词
        </div>
        <div class="btn" id="yxp-before-save" @click="handleSave">开始识记</div>
      </div>
    </div>
    <div class="yxp-word-box" id="wordBox">
      <div class="yxp-wordList-box">
        <div class="yxp-wordList-box-item">
          <div class="yxp-wordList-main">
            <div
              class="yxp-wordList-item list-item"
              v-for="(item, i) in dataList"
              :key="`${item.id}-${i}`"
              @click="handlePlay(item, i)"
            >
              <div
                class="yxp-wordList-item-l"
                :class="{ active: item.num > 0 && curIndex === i }"
              >
                <span class="word-en">{{ item.word }}</span>
                <span
                  class="word-zh"
                  v-show="item.num === 2 && curIndex === i"
                  >{{ item.translate }}</span
                >
              </div>
              <div class="yxp-wordList-item-r">
                <div
                  class="success img1"
                  v-show="item.isSuccess"
                  :id="'yxp-before-success28-'+item.word"
                  @click.stop="handleSelectSuccess(i, item)"
                ></div>
                <div
                  class="success img2"
                  v-show="!item.isSuccess"
                  :id="'yxp-before-success29-'+item.word"
                  @click.stop="handleSelectSuccess(i, item)"
                ></div>
                <div
                  class="success img3"
                  v-show="!item.isError"
                  :id="'yxp-before-error30-'+item.word"
                  @click.stop="handleSelectError(i, item)"
                ></div>
                <div
                  class="success img4"
                  v-show="item.isError"
                  :id="'yxp-before-error31-'+item.word"
                  @click.stop="handleSelectError(i, item)"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <audio ref="audio"></audio>
    <div class="yxp-wordList-mark" v-if="isShow"></div>
    <div class="yxp-before-pop" v-if="isShow">
      <div class="close" @click="handleClose"></div>
      <p class="text text-one">
        认识的词点击对勾，标记为<img src="@/assets/word/success.png" />
      </p>
      <p class="text">
        不熟悉的点击叉号，标记为<img src="@/assets/word/error-sel.png" />
      </p>
      <p class="tips">点击[开始识记]后会把标记红叉的单词进行识记学习</p>
      <div class="btn" @click="handleClose">知道了</div>
    </div>
    <div class="mark" v-if="isShow || isBack"></div>
    <div class="yxp-wordList-pop" v-if="isBack">
      <div class="close" @click="isBack = false"></div>
      <!-- <img src="@/assets/word/close-icon.png" class="close" @click="isBack = false"/> -->
      <p class="tips">是否放弃选词</p>
      <div class="btn">
        <span class="btn-item" @click="handleSure" id="yxp-before-sure">确定</span>
        <span class="btn-item" @click="isBack = false" id="yxp-before-reset">取消</span>
      </div>
    </div>
    <Timetips ref="timetips"></Timetips>
  </div>
</template>
<script>
import {
  fetchSplitWrod,
  readUpword,
  wordPrint,
  fetchReadWord,
} from "@/services/super-read";
import { SUCCESS_CODE } from "@/utils/const";
const completePng = require("assets/super-read/word-complete.png");
import storage from '@/utils/storage.js'
import Timetips from "@/components/Timetips";
export default {
  name: "beforeStudy",
  components: {
    Timetips
  },
  data() {
    return {
      detailPath:
        +this.$route.query.type === 6
          ? "/super-read/pushblank"
          : "/super-read/pushword",
      isShow: true,
      isBack: false,
      isNext: true,
      isPrint: false,
      study_model: -1,
      package_id: -1,
      course_type: 0,
      modal: 0, // 判断路由来源
      pageSize: 20,
      pageIndex: 1,
      total: 0,
      page: 0,
      initData: [],
      dataList: [],
      canArr: [],
      canSub: [],
      canNotArr: [],
      checkData: [],
      successNum: 0,
      errorNum: 0,
    };
  },
  created() {
    this.initDataList();
  },
  methods: {
    initDataList() {
      let { id, type, read, modal } = this.$route.query;
      if (read) {
        this.$loading.show();

        fetchReadWord({
          question_id: this.$route.query.id,
        })
          .then((res) => {
            if (res.code === SUCCESS_CODE) {
              if (!res.data.length) {
                this.$yxpConfirm({
                  msg: `<img width="223" style="margin: -20px 0;" src="${completePng}" alt=""/>
             <p>您没有需要识记的生词，开始实战模拟训练吧~</p>
            `,
                  type: "alert",
                  html: true,
                  maskClosable: false,
                  alertBtnText: "确定",
                  closable: false
                })
                  .then(() => {
                    // this.$router.replace({
                    //   path: this.detailPath,
                    //   query: { ...this.$route.query },
                    // });
                    this.$router.go(-1)
                  })
                  .catch(() => {});
              }
              res.data.map((v) => {
                v.num = 0;
                v.isSuccess = false;
                v.isError = false;
              });
              this.dataList = res.data;
            }
          })
          .finally(() => {
            this.$loading.hide();
          });
      } else {
        this.$loading.show();

        fetchSplitWrod({
          question_id: id,
          question_type: type,
        })
          .then((res) => {
            if (+res.code === SUCCESS_CODE) {
              if (!res.data.length) {
                this.$yxpConfirm({
                  msg: `<img width="223" style="margin: -20px 0;" src="${completePng}" alt=""/>
             <p>您没有需要识记的生词，开始实战模拟训练吧~</p>
            `,
                  type: "alert",
                  html: true,
                  maskClosable: false,
                  alertBtnText: "确定",
                  closable: false
                })
                  .then(() => {
                    // this.$router.replace({
                    //   path: this.detailPath,
                    //   query: { ...this.$route.query },
                    // });
                    // this.$router.go(-1)
                    this.$router.push({
                      path: this.detailPath,
                      query: this.$route.query
                    })
                  })
                  .catch(() => {});
              }
              res.data.map((v) => {
                v.num = 0;
                v.isSuccess = false;
                v.isError = false;
              });
              this.dataList = res.data;
            }
          })
          .finally(() => {
            this.$loading.hide();
          });
      }
    },
    handleSave() {
      let modal = +this.$route.query.modal
      this.modal = modal
      if (modal === 1) {
        if (this.canArr.length + this.canNotArr.length !== this.dataList.length) {
          this.$toast("所有的单词都进行学前检测才能开始识记哦~");
          return;
        }
      }
      if (this.canNotArr.length > 0) {
        if (!this.isPrint) {
          this.isPrint = true;
          this.handlePrint();
          setTimeout(() => {
            this.isPrint = false;
          }, 60000);
        } else {
          this.$toast("60s内不能频繁打印~");
        }
      } else {
        if (modal === 1) {
          this.SaveWord()
        } else {
          this.$router.go(-1)
        }
      }
    },
    async handlePrint() {
      let page = Math.ceil(this.checkData.length / 5);
      let wordData = [];
      for (let i = 0; i < page; i++) {
        let start = i * 5
        let end = (i + 1) * 5
        let data = this.checkData.slice(start, end)
        let obj = {
          page: i + 1,
          status: false,
          isEnd: false,
          isCheck: false,
          data: data
        }
        wordData.push(obj)
      }
      storage.set('paperData',wordData)
      storage.set("canArr",this.canArr)
      let params = {
        question_type: "1",
        word_list: this.canNotArr.join(","),
        from: "word_remember",
        question_id: this.$route.query.id,
      };
      let data = await wordPrint(params);
      if (data.code === 1) {
        this.$toast("已选单词已提交后台打印");
        this.$router.replace({
          path: "/super-read/wordMemory",
          query: { ...this.$route.query },
        });
      } else {
        this.$toast("打印过于频繁");
      }
    },
    // 一眼会识记
    async SaveWord() {
      this.$loading.show();
      let params = {
        can: this.canArr.join(","),
        can_not: this.canNotArr.join(","),
        question_id: this.$route.query.id,
        question_type: this.$route.query.type,
      };
      let data = await readUpword(params);
      if (data.code === 1) {
        this.$loading.hide();
        this.$yxpConfirm({
          msg: `<img width="223" style="margin: -20px 0;" src="${completePng}" alt=""/>
             <p>开始实战模拟训练吧~</p>
            `,
          type: "alert",
          html: true,
          maskClosable: false,
          alertBtnText: "确定",
          closable: false
        })
          .then(() => {
            this.$router.replace({
              path: this.detailPath,
              query: { ...this.$route.query },
            });
          })
          .catch(() => {});
      } else {
        this.$loading.hide();
        this.$toast(data.info);
      }
    },
    // 播放语音
    handlePlay(item, i) {
      this.curIndex = i;
      let num = item.num;
      num++;
      if (num > 2) num = 1;
      this.$set(item, "num", num);
      let audio = this.$refs.audio;
      audio.src = item.project_voice;
      audio.play();
      this.dataList.map((elem, index) => {
        if (index !== i) {
          this.$set(elem, "num", 0);
        }
      });
    },
    handleSelectSuccess(i, item) {
      if (item.isSuccess) return;
      this.successNum++;
      let obj = this.dataList[i];
      this.$set(obj, "isError", false);
      this.$set(obj, "isSuccess", true);
      let index = this.checkData.findIndex((elem) => {
        return elem.id === item.id;
      });
      if (index > -1) {
        this.checkData.splice(index, 1);
      }
      if (this.canArr.indexOf(item.id) === -1) {
        this.canArr.push(item.id);
      }
      if (this.canNotArr.indexOf(item.id) > -1) {
        let index = this.canNotArr.indexOf(item.id);
        this.canNotArr.splice(index, 1);
        this.errorNum--;
      }
    },
    handleSelectError(i, item) {
      if (item.isError) return;
      if (this.canNotArr.length === 45) {
        this.$toast("单词已选够45个了，开始识记把~");
        return;
      }
      this.errorNum++;
      this.checkData.push(item);
      let obj = this.dataList[i];
      this.$set(obj, "isSuccess", false);
      this.$set(obj, "isError", true);
      if (this.canNotArr.indexOf(item.id) === -1) {
        this.canNotArr.push(item.id);
      }
      if (this.canArr.indexOf(item.id) > -1) {
        let index = this.canArr.indexOf(item.id);
        this.canArr.splice(index, 1);
        this.successNum--;
      }
    },
    handleClose() {
      this.isShow = false;
    },
    handleBack() {
      this.isBack = true;
    },
    async handleSure() {
      this.$router.go(-1);
    },
  },
  beforeDestroy() {
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
};
</script>
<style lang="less" scoped>
.before-word {
  padding-bottom: 60px;
}
.yxp-wordList-top {
  .back {
    position: absolute;
    left: 40px;
    top: 27px;
    width: 30px;
    height: 27px;
    cursor: pointer;
  }
  .yxp-top-r {
    position: absolute;
    right: 40px;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    .success {
      font-size: 20px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #27bfa3;
      margin-right: 29px;
      img {
        width: 20px;
        height: 14px;
        display: inline-block;
        vertical-align: middle;
        margin-right: 10px;
      }
    }
    .error {
      font-size: 20px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #ff6767;
      margin-right: 50px;
      img {
        width: 18px;
        height: 18px;
        display: inline-block;
        vertical-align: middle;
        margin-right: 10px;
      }
    }
    .btn {
      width: 140px;
      height: 46px;
      line-height: 46px;
      font-size: 20px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #fff;
      background: linear-gradient(
        360deg,
        rgba(71, 203, 179, 1) 0%,
        rgba(81, 211, 176, 1) 100%
      );
      box-shadow: 0px 5px 10px rgba(59, 201, 164, 0.3);
      border-radius: 30px;
      cursor: pointer;
      &:hover {
        background: linear-gradient(
          360deg,
          rgba(39, 178, 152, 1) 0%,
          rgba(52, 203, 163, 1) 100%
        );
        box-shadow: 0px 5px 10px rgba(59, 201, 164, 0.3);
      }
    }
  }
}

.yxp-wordList-page {
  width: 360px;
  height: 60px;
  line-height: 60px;
  font-size: 24px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #fff;
  background: linear-gradient(
    360deg,
    rgba(71, 203, 179, 1) 0%,
    rgba(81, 211, 176, 1) 100%
  );
  box-shadow: 0px 5px 10px rgba(59, 201, 164, 0.3);
  border-radius: 10px;
  margin: 40px auto;
  cursor: pointer;
  &:hover {
    background: linear-gradient(
      360deg,
      rgba(39, 178, 152, 1) 0%,
      rgba(52, 203, 163, 1) 100%
    );
  }
  &:active {
    background: linear-gradient(
      180deg,
      rgba(71, 203, 179, 1) 0%,
      rgba(81, 211, 176, 1) 100%
    );
  }
}
.yxp-wordList-mark {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}
.yxp-before-pop {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 480px;
  height: 355px;
  text-align: center;
  background: #fff;
  border-radius: 20px;
  z-index: 1000;
  .close {
    position: absolute;
    right: 20px;
    top: 15px;
    width: 20px;
    height: 20px;
    background: url(../../../assets/word/close-icon.png) no-repeat;
    background-size: 20px 20px;
    cursor: pointer;
    &:hover {
      background-image: url(../../../assets/word/close-hover.png);
    }
  }
  .text-one {
    margin-top: 59px;
    margin-bottom: 19px;
  }
  .text {
    font-size: 24px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #333333;
    img {
      width: 30px;
      height: 30px;
      margin-left: 10px;
      vertical-align: middle;
    }
  }
  .tips {
    font-size: 18px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #999;
    margin-top: 30px;
  }
  .btn {
    width: 350px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-size: 18px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #fff;
    background: #27bfa3;
    border-radius: 100px;
    margin: 40px auto 0;
    cursor: pointer;
    &:hover {
      background: #18a38a;
    }
  }
}
</style>
